package com.yan.jwt;

import io.jsonwebtoken.*;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.fastjson.JSONObject;
import com.yan.utils.GsonUtil;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;
import java.util.Map;

public class JwtUtil {

    private static final Logger logger = LoggerFactory.getLogger(JwtUtil.class);

    private static final String PROFILES = "mobile";

    /**
     * 由字符串生成加密key
     *
     * @return
     */
    public static SecretKey generalKey() {
        String stringKey = PROFILES + "7786df7fc3a34e26a61c034d5ec8245d";
        byte[] encodedKey = Base64.decodeBase64(stringKey);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     * 创建jwt
     *
     * @param id
     * @param subject
     * @param ttlMillis
     * @return
     * @throws Exception
     */
    public static String createJWT(String id, String subject, long ttlMillis) throws Exception {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        SecretKey key = generalKey();
        JwtBuilder builder = Jwts.builder().setId(id).setIssuedAt(now).setSubject(subject).signWith(signatureAlgorithm,
                key);
        if (ttlMillis >= 0) {
            long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }
        return builder.compact();
    }

    /**
     * 解密jwt
     *
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) {
        try {
            SecretKey key = generalKey();
            Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(jwt).getBody();
            return claims;
        } catch (ExpiredJwtException expiredJwtException) {
            logger.error("JWT超时,exception:[{}]", expiredJwtException.getMessage());
            return null;
        } catch (Exception ex) {
            logger.error("解析jwt错误,exception:", ex);
            return null;
        }
    }

    /**
     * 生成subject信息
     *
     * @param user
     * @return
     */
    public static String generalSubject(YbfUserBase user) {
        JSONObject jo = new JSONObject();
        jo.put("userId", user.getId());
        jo.put("nickname", user.getNickName());
        return jo.toJSONString();
    }

    public static void main(String args[]) throws NumberFormatException, Exception {

        YbfUserBase ybfUserBase = new YbfUserBase();
        ybfUserBase.setId("1");
        ybfUserBase.setNickName("nickName");
        String json = generalSubject(ybfUserBase);

        String createJwtStr = createJWT("1", json, 1000 * 6);
        System.out.println(createJwtStr);
        //Thread.sleep(1000 * 10);
        String data = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJqd3QiLCJpYXQiOjE1MDIxOTIxMTEsInN1YiI6IntcImlkXCI6XCJISExZMDAwMDAwMDRcIixcInBob25lTnVtXCI6XCIxMzU3MDE4NTMyN1wiLFwiaW1hZ2VTcmNcIjpcImh0dHA6Ly90cC4xMzMyMi5jb20vaW1nLzIwMTctMDYtMDYvOTIxMmYyNjUtOGYyOC00MGUzLTkwMzItYTJjYjQxMmU2MzNjLmpwZ1wiLFwibmlja05hbWVcIjpcIuivuOiRm-eci-ebmFwifSJ9.fVNhV2XD3Pah8bfdqMq9M2QmvwQwfnnzQyIAG7jMMHQ";

        Claims claims = parseJWT(createJwtStr);
        System.out.println("content =====" + parseJWT(createJwtStr));
        if (claims != null) {
            Map<String, Object> map = GsonUtil.jsonToMap(claims.getSubject());
            System.out.println(map.get("nickname"));
        }

        System.out.println(json);

        System.out.println(parseJWT(data));
        System.out.println(parseJWT(data).getSubject() + "\n");

        String id = (String) GsonUtil.jsonToMap(parseJWT(data).getSubject()).get("id");

        System.out.println(id + "\n");

        System.out.println("token====" + parseJWT(null));

    }
}
